package com.hd.job;

import java.util.ArrayList;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import com.hd.commons.scan.SpringContextUtil;
import com.hd.entity.job.QuartzScheduleJob;
import com.hd.util.JsonUtil;
@PersistJobDataAfterExecution
public class QuartzJobFactory implements Job{
	private static final Logger log=LoggerFactory.getLogger(QuartzJobFactory.class);
	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		 	QuartzScheduleJob scheduleJob = (QuartzScheduleJob) jobExecutionContext.getMergedJobDataMap().get("scheduleJob");
	        //获取service层接口名和接口方法名
	        String springBeanName = scheduleJob.getClassName();
	        String methodName = scheduleJob.getMethodName();
	        //获取参数数组和参数类型数组
	        ArrayList paramArray = scheduleJob.getParamArray();
	       if(paramArray==null) {
	    	   paramArray=new ArrayList();
	       }else {
	    	   System.out.println(JsonUtil.toJson(paramArray));
	       }
	        Class[] paramType = new Class[paramArray.size()];
	        for (int i = 0; i < paramArray.size(); i++) {
	            paramType[i] = paramArray.get(i).getClass();
	        }
	        /**
	         * 反射运行service层的方法
	         */
	        System.out.println("springBeanName="+springBeanName);
	        Object bean = SpringContextUtil.getBean(springBeanName);
	        log.info("bean="+bean);
	        java.lang.reflect.Method method = ReflectionUtils.findMethod(bean.getClass(), methodName, paramType);
	        ReflectionUtils.invokeMethod(method, bean, paramArray.toArray());
	 
	        log.info("任务名称 = [" + scheduleJob.getJobName() + "]," +
	                "任务调用的类=[" + scheduleJob.getClassName() + "]," +
	                "任务调用的方法=[" + scheduleJob.getMethodName() + "]---->>成功启动运行");

	}

}
